package com.point.business.servlets;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.JsonObject;
import com.point.business.database.managers.UsersManager;
import com.point.business.database.model.User;
import com.point.business.util.UserNotFoundException;

/**
 * Servlet Filter implementation class SecurityFilter
 */
public class ServletFilter implements Filter {
	private static Logger logger = Logger.getLogger(ServletFilter.class);

	/**
	 * Default constructor.
	 */
	public ServletFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		User user = (User) httpRequest.getSession().getAttribute("user");
		if (user == null) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String pathInfo = ((HttpServletRequest) request).getRequestURI();
			try {
				user = UsersManager.getInstance().login(username, password);
				if (user != null) {
					request.setAttribute("userId", user.getId());
				} else {
					throw new UserNotFoundException("User not " + username
							+ " found");
				}
			} catch (UserNotFoundException e) {
				logger.error(e);
				redirectToErrorPage(httpRequest, httpResponse);
			}
			if (user == null) {
				redirectToErrorPage(httpRequest, httpResponse);
			} else {
				if (pathInfo != null) {
					if (pathInfo.endsWith("SearchSLServlet")) {
						if (user.isCanDoSL()) {
							chain.doFilter(request, response);
						} else {
							redirectToErrorPage(httpRequest, httpResponse);
						}
					} else if (pathInfo.endsWith("SearchNOServlet")) {
						if (user.isCanDoNO()) {
							chain.doFilter(request, response);
						} else {
							redirectToErrorPage(httpRequest, httpResponse);
						}
					}
					if (pathInfo.endsWith("SearchNDServlet")) {
						if (user.isCanDoND()) {
							chain.doFilter(request, response);
						} else {
							redirectToErrorPage(httpRequest, httpResponse);
						}
					}
					if (pathInfo.endsWith("SearchUOPBServlet")) {
						if (user.isCanDoUOPB()) {
							chain.doFilter(request, response);
						} else {
							redirectToErrorPage(httpRequest, httpResponse);
						}
					}
				} else {
					redirectToErrorPage(httpRequest, httpResponse);
				}
			}
		} else {
			request.setAttribute("userId", user.getId());
			chain.doFilter(request, response);
		}
	}

	private void redirectToErrorPage(HttpServletRequest request,
			HttpServletResponse response) {
		logger.warn("The following IP address: " + request.getRemoteAddr()
				+ " tried to enter the site with incorrect priveleges");

		try {
			JsonObject jsono = new JsonObject();
			jsono.addProperty("msg", "Not enough privileges");
			response.getOutputStream().print(jsono.toString());
			response.setStatus(401);

		} catch (IOException e) {
			logger.error(e);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
